<template>
  <div class="form-page">
    <Card :bordered="false" :dis-hover="true">
      <p slot="title" style="color: #666;">
        <span
          class="iconfont icon-changyongtubiao-xianxingdaochu-zhuanqu-"
          style="font-size: 20px;"
        ></span> 新增轮播页
      </p>
      <p slot="extra" style="color: #999;font-size: 12px;">
        <label style="color: #FF3B30;">*</label> 为必填
      </p>

      <Form
        ref="formValidate2"
        :model="bloc.model"
        :rules="ruleValidate3"
        :label-width="111"
        style="padding:50px 10% 0 10%;width: 860px"
      >

        <FormItem label="轮播页归属(品牌商):" prop="companyId" required v-if="tepee === '1'">
          <CompanySeletorSingle :companyId="bloc.model.companyId" style="width: 400px"
                                @on-change="value => companyChange(value)" v-if="tepee === '1'"></CompanySeletorSingle>
        </FormItem>
<!--        <FormItem label="轮播图归属(品牌商):" prop="companyId" required>-->
<!--          <CompanySeletorSingle :companyId="bloc.model.companyId" style="width: 400px"-->
<!--                                @on-change="value => companyChange(value)" v-if="tepee === '2'" disable></CompanySeletorSingle>-->
<!--        </FormItem>-->

        <FormItem label="轮播页归属(经销商):" prop="agentId" v-if="tepee === '1'">
          <i-select v-model="bloc.model.agentId" filterable style="width: 400px" clearable v-if="tepee === '1'">
            <i-option v-for="item in bloc.sortList" :value="item.id" :key="item.id">{{ item.agentName }}</i-option>
          </i-select>
        </FormItem>
<!--        <FormItem label="轮播图归属(经销商):" prop="agentId" v-if="tepee === '2'">-->
<!--          <i-select v-model="bloc.model.agentId" filterable style="width: 400px" clearable disabled v-if="tepee === '2'">-->
<!--            <i-option v-for="item in bloc.sortList" :value="item.id" :key="item.id">{{ item.agentName }}</i-option>-->
<!--          </i-select>-->
<!--        </FormItem>-->

        <FormItem label="图片名称:" prop="bannername" required>
          <Input v-model="bloc.model.bannername" placeholder="最多15个字" style="width: 400px" :maxlength="15"/>
        </FormItem>
        <FormItem label="展示时间:" required>
            <Row>
                <Col span="11">
                  <FormItem prop="startTime">
                    <DatePicker style="width: 100%;" type="datetime" format="yyyy-MM-dd HH:mm:ss" placeholder="开始时间" v-model="bloc.model.startTime"></DatePicker>
                  </FormItem>
                </Col>
                <Col span="2" style="text-align: center">-</Col>
                <Col span="11">
                  <FormItem prop="endTime">
                    <DatePicker style="width: 100%;" type="datetime" format="yyyy-MM-dd HH:mm:ss" placeholder="结束时间" v-model="bloc.model.endTime"></DatePicker>
                  </FormItem>
                </Col>
            </Row>
        </FormItem>
        <FormItem label="图片:" prop="imageurl" required>
          <div class="demo-upload-list" v-for="(item, index) in fileList" :key="index">
            <template v-if="item.status1 === 'finished'">
              <img :src="item.imageurl">
              <div class="demo-upload-list-cover">
                <Icon type="ios-eye-outline" @click.native="handleView(item.imageurl)"></Icon>
                <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
              </div>
            </template>
            <template v-else>
              <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
            </template>
          </div>
          <Upload
            ref="upload"
            :show-upload-list="false"
            :action="uploadAction"
            :max-size="2048"
            :format="['jpg','png','gif']"
            :headers="uploadHeaders"
            :on-format-error="handleFormatError1"
            :on-exceeded-size="handleMaxSize1"
            :on-success="handleSuccess"
            style="display: inline-block;width:58px;margin-left:15px"
          >
<!--            :before-upload="beforeUpload"-->
            <div style="width: 58px;height:58px;line-height: 58px;">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
            <Modal title="View Image" v-model="visible">
              <img :src="imgUrl" v-if="visible" style="width: 100%">
            </Modal>
          </Upload>
          <div><p>JPG、PNG、GIF格式且小于2M的图片，推荐尺寸为995*667</p></div>
        </FormItem>

        <FormItem label="排序:" prop="sort" required>
          <Input v-model="bloc.model.sort" style="width: 400px" :maxlength="10"/>
        </FormItem>

<!--        <FormItem label="跳转商品:" prop="productname">-->
<!--          <Input v-model="bloc.model.productName" @on-change="inputChange" style="width: 400px"/>-->
<!--          <option>-->
<!--          </option>-->
<!--        </FormItem>-->

        <FormItem label="跳转商品:" prop="modelname">
          <ProductSelector
            style="width: 400px; margin-right: 10px"
            :modelId="bloc.model.modelId"
            @on-change="(value) => (bloc.model.modelId = value)"
          ></ProductSelector>
        </FormItem>

        <FormItem label="跳转链接(外部):" prop="linkurl">
          <Input v-model="bloc.model.linkurl" style="width: 400px" :placeholder="plToplay"/>
        </FormItem>
        <FormItem label="跳转链接(内部):" prop="linkurlWebview">
          <Input v-model="bloc.model.linkurlWebview" style="width: 400px" :placeholder="plToplay"/>
        </FormItem>
<!--        <FormItem label="后续动作:" prop="actionData">-->
<!--          <RadioGroup v-model="bloc.model.actions">-->
<!--            <Radio :label= 1 >app内打开</Radio>-->
<!--            <Radio :label= 2 >app外打开</Radio>-->
<!--            <Radio :label= 3 >链接到商品</Radio>-->
<!--          </RadioGroup>-->
<!--        </FormItem>-->
      </Form>
      <div style="margin: 20px 0px 35px 25px;">
        <Button style="width: 100px;height: 40px;" @click="handleCancel()">返回</Button>
        <AppButton
          ref="save"
          style="margin-left: 30px;width: 100px;height: 40px;"
          type="primary"
          :disabled="bloc.isDetail"
          @click="addModel('formValidate2')"
        >确认
        </AppButton>
      </div>
    </Card>
  </div>
</template>

<script lang="ts">

import {Component, Vue} from 'vue-property-decorator';
    import {store} from '@/store/Store';
    import {baseUrl} from '@/base/Request';
    import {Route} from 'vue-router';
    import {FormBloc} from './AddBloc';
    import {isEmpty} from '@/base/util/Strings';
    import {AppButton} from '@/type/AppButton';
    import { getValidateHttp2 } from '@/base/util/Validate';
    import ProductSelector from '@/component/ProductSelector.vue';
    import CompanySeletorSingle from '@/component/CompanySeletorSingle.vue';

    @Component({
        components: {ProductSelector, CompanySeletorSingle}
    })

    export default class extends Vue {
        disabled: boolean = true;
        timer: number | undefined;

        beforeRouteEnter(to: Route, from: Route, next: (vm: any) => void) {
            next(vm => {
                vm.bloc.type = vm.tepee;
                if (vm.$route.query.agentId === 1) {
                    vm.disabled = false
                }
                if (vm.$route.query.companyId === 0) {
                    vm.disabled = false
                }
                if (isNaN(Number(vm.$route.query.companyId))) {
                    vm.bloc.companyId = 0;
                } else {
                    vm.bloc.companyId = Number(vm.$route.query.companyId);
                }
                vm.bloc.agentId = Number(vm.$route.query.agentId);
                vm.bloc.model.agentId = vm.bloc.agentId;
                vm.bloc.model.companyId = vm.bloc.companyId;
                vm.bloc.getCompanyList(vm.bloc.company.pageIndex, vm.bloc.company.pageSize, 'ASC');
                vm.bloc.getAllSort(1, 1000, 'ASC', 1);
                // vm.bloc.putDeviceModelGather()
            });
        }

        bloc = new FormBloc();
        validateId = (rule: any, value: string, callback: any) => {
            isEmpty(this.bloc.model.companyId) || this.bloc.model.companyId === 0
                ? callback(new Error('所属品牌商不能为空')) : callback();
        };
        // validateId2 = (rule: any, value: string, callback: any) => {
        //     if (!isEmpty(this.bloc.model.linkurl) && this.bloc.model.actions !== 0) {
        //         callback();
        //     } else if (!isEmpty(this.bloc.model.linkurl) || this.bloc.model.actions !== 0) {
        //         callback(new Error('跳转链接和后续动作不能只填一项'));
        //     } else {
        //         callback();
        //     }
        // };
        validateId2 = (rule: any, value: string, callback: any) => {
            if ((!isEmpty(this.bloc.model.linkurl)||!isEmpty(this.bloc.model.linkurlWebview)) && !(isEmpty(this.bloc.model.modelId) || this.bloc.model.modelId === '0')) {
                callback(new Error('跳转链接和跳转商品不能同时填写'));
            } else {
                callback();
            }
        };
        validateId3 = (rule: any, value: string, callback: any) => {
            if (!getValidateHttp2(this.bloc.model.linkurl) && !isEmpty(this.bloc.model.linkurl)) {
                callback(new Error('跳转链接格式不正确,请以https://开头'));
            } else {
                callback();
            }
        };
        validateId4 = (rule: any, value: string, callback: any) => {
            if (!getValidateHttp2(this.bloc.model.linkurlWebview) && !isEmpty(this.bloc.model.linkurlWebview)) {
                callback(new Error('跳转链接格式不正确,请以https://开头'));
            } else {
                callback();
            }
        };
        get tepee() {
            return store.state.user.tepee
        }
        get uploadHeaders() {
            return {
                'Authorization': 'Bearer ' + store.state.auth.accessToken
            }
        };

        get uploadAction() {
            return `${baseUrl}/api/upload/image`
        }

        imgUrl = '';
        visible = false;
        get plToplay() {
            return this.bloc.model.actions !== 0
                ? '请填写以https://开头的地址'
                : '';
        }
        get fileList() {
            return this.bloc.fileList.map(x => {
                return {'name': 'name', 'imageurl': x, 'status1': 'finished'};
            });
        }

        handleView(url) {
            this.imgUrl = url;
            this.visible = true;
        }

        handleRemove(file) {
            this.bloc.fileList.splice(this.bloc.fileList.indexOf(file), 1);
        }

        ruleValidate3: any = {
            companyId: [
                {validator: this.validateId, trigger: 'blur'}
            ],
            imageurl: [
                {required: true, message: '轮播页图片不能为空', trigger: 'change'}
            ],
            bannername: [{required: true, message: '轮播页名称不能为空', trigger: 'blur'}],
            // actionData: [{validator: this.validateId2, trigger: 'blur'}],
            modelname: [{validator: this.validateId2, trigger: 'blur'}],
            linkurl: [{validator: this.validateId3, trigger: 'blur'}],
            linkurlWebview: [{validator: this.validateId4, trigger: 'blur'}]
        };
        $refs!: {
            save: AppButton
            formValidate2: HTMLFormElement
        };
        enable = false;
        switchStatus(status) {
            if (status) {
                this.bloc.model.status = 1
            } else {
                this.bloc.model.status = 0
            }
        };
        companyChange(companyId) {
            this.bloc.model.companyId = companyId;
            this.bloc
                .getAllSort(this.bloc.angent.pageIndex, 1000, 'DESC')
                .then((res) => {})
                .finally(() => {});
        }
        // 添加
        addModel(name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    this.$refs.save.bloc.loading = true;
                    if (isNaN(this.bloc.model.agentId)) {
                        this.bloc.model.agentId = 1;
                    }
                    if (this.tepee !== '1') {
                        this.bloc.model.agentId = store.state.user.agent.id;
                        this.bloc.model.companyId = store.state.user.agent.companyId;
                    }
                    if (isEmpty(this.bloc.model.modelId)) {
                        this.bloc.model.modelId = '0';
                    }
                    if(this.bloc.model.linkurl){
                      this.bloc.model.actions = 2;
                    }
                    if(this.bloc.model.linkurlWebview){
                      this.bloc.model.actions = 1;
                    }
                    if (!isEmpty(this.bloc.model.modelId) && isEmpty(this.bloc.model.linkurl) && isEmpty(this.bloc.model.linkurlWebview) && this.bloc.model.modelId !== '0') {
                        this.bloc.model.linkurl = this.bloc.model.modelId;
                        this.bloc.model.actions = 3;
                    }
                    this.bloc.addModel(this.bloc.model).then(res => {
                        this.$Message.success('保存成功');
                        this.$refs.save.bloc.loading = false;
                        this.handleCancel();
                    }).catch(err => {
                        // this.$Message.error('保存失败');
                        this.$Message.error(err.message);
                        this.$refs.save.bloc.loading = false;
                    });
                }
            });
        }

        handleFormatError1(file) {
            // this.$Notice.warning({
            //   title: '文件格式不正确',
            //   desc: file.name + '文件格式不正确，请选择格式为 JPG、PNG格式的文件'
            // });
            this.$Message.error('请选择格式为JPG、PNG、GIF格式的文件')
        }

        handleMaxSize1(file) {
            this.$Message.error('图片大小不能超过2M')
        }
        // beforeUpload(file) {
        //   const img = new Image();
        //   img.src = URL.createObjectURL(file);
        //   img.onload = () => {
        //       // console.log(img.width, img.height);
        //   }
        // }

        handleSuccess(res, file) {
            this.bloc.model.imageurl = res.data[0];
            if (this.bloc.fileList.length > 0) {
                this.bloc.fileList = []
            }
            this.bloc.fileList.push(this.bloc.model.imageurl)
        }
        handleCancel() {
            this.$router.push({path: `/banners/nav/banner`});
        }
    }
</script>

<style lang="less" scoped>
  /deep/ .ivu-form-item-content {
    display: flex !important;
    justify-content: start !important;
    align-items: center !important;
  }
  /deep/ .ivu-form-item-label {
    padding-top: 0px;
  }
</style>
